package com.dy.web.controller.system;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.dy.common.core.domain.entity.SysDept;
import com.dy.common.core.domain.entity.SysUser;
import com.dy.common.utils.DateUtils;
import com.dy.common.utils.StringUtils;
import com.dy.common.utils.bean.BeanUtils;
import com.dy.system.domain.FreshMedicalMachine;
import com.dy.system.domain.InspectionReport;
import com.dy.system.domain.MedicalEquipmentReportLog;
import com.dy.system.domain.vo.FreshMedicalMachineVo;
import com.dy.system.domain.vo.InstitutionDetailVo;
import com.dy.system.domain.vo.MedicalEquipmentReportLogVo;
import com.dy.system.service.*;
import com.github.pagehelper.PageHelper;
import org.jetbrains.annotations.Nullable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.dy.common.annotation.Log;
import com.dy.common.core.controller.BaseController;
import com.dy.common.core.domain.AjaxResult;
import com.dy.common.enums.BusinessType;
import com.dy.system.domain.MedicalInstitution;
import com.dy.common.utils.poi.ExcelUtil;
import com.dy.common.core.page.TableDataInfo;

/**
 * 机构
 *
 * @author anps
 * @date 2022-07-27
 */
@RestController
@RequestMapping("/system/institution")
public class MedicalInstitutionController extends BaseController{
    @Autowired
    private IMedicalInstitutionService medicalInstitutionService;
    @Autowired
    private ISysDictDataService sysDictDataService;
    @Autowired
    private IFreshMedicalMachineService freshMedicalMachineService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private IInspectionReportService inspectionReportService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IMedicalEquipmentReportLogService medicalEquipmentReportLogService;


    @GetMapping("/get/ins/option")
    public AjaxResult getInstitutionByDeptId(@RequestParam Long deptId){
        MedicalInstitution medicalInstitution = new MedicalInstitution();
        medicalInstitution.setDeptId(deptId);
        medicalInstitution.setStatus("0");
        List<MedicalInstitution> institutionList = medicalInstitutionService.selectMedicalInstitutionList(medicalInstitution);
        List<Map<String,Object>> mapList = new ArrayList<>();
        institutionList.forEach(m ->{
            Map<String,Object> map = new HashMap<>(2);
            map.put("id",m.getId());
            map.put("name",m.getName());
            mapList.add(map);
        });
        return AjaxResult.success(mapList);
    }


    /***
     * 获取机构详情（后台接口）
     * @param id 机构ID
     * @return
     */
    @GetMapping("/get/detail")
    public AjaxResult getInstitutionDetail(@RequestParam Long id){
        InstitutionDetailVo detailVo = new InstitutionDetailVo();
        //查询机构信息
        MedicalInstitution institution = getMedicalInstitution(id);
        detailVo.setMedicalInstitution(institution);
        //查询用户信息
        SysUser sysUser = sysUserService.selectUserByUserName(institution.getCreateBy());
        detailVo.setUserInfo(sysUser);
        List<InspectionReport> inspectionReportList = new ArrayList<>();
        //查询检测报告
        String img = "https://dyep.cc/prod-api";
        for (int a = 1; a <=4; a ++){
            InspectionReport report = inspectionReportService.selectInspectionReportByInsId(id,a);
            if (report == null){
                report = new InspectionReport();
                report.setSession(String.valueOf(a));
                report.setUploadStatus("未上传");
                report.setSplicingStr(getSubDateStr(String.valueOf(a)));
            }else{
                report.setSplicingStr(getSubDateStr(String.valueOf(a)));
                report.setUploadStatus("已上传");
            }
            report.setReportUrl(StringUtils.isNoneBlank(report.getReportUrl()) ? img + report.getReportUrl() : "");
            report.setYeayName(DateUtils.parseDateToStr(DateUtils.YYYY,new Date()));
            inspectionReportList.add(report);
        }
        detailVo.setInspectionReportList(inspectionReportList);
        //查询设备信息
        FreshMedicalMachine m = new FreshMedicalMachine();
        m.setInstitutionId(id);
        List<FreshMedicalMachine> machineList = freshMedicalMachineService.selectFreshMedicalMachineList(m);
        detailVo.setMedicalMachineList(machineList);
        return AjaxResult.success(detailVo);
    }



    public String getSubDateStr(String session){
        String dataFw = null;
        switch (session){
            case "1":
                dataFw = "01月01日~03月31日";
                break;
            case "2":
                dataFw = "04月01日~06月30日";
                break;
            case "3":
                dataFw = "06月01日~09月30日";
                break;
            default:
                dataFw = "10月01日~12月31日";
                break;
        }
        return dataFw;
    }




    /***
     * 医疗机构 applet
     * @return
     */
    @GetMapping("/applet/list")
    public AjaxResult getEquipmentReportLogDataList(Long deptId,Integer status,String name) {

        MedicalInstitution medicalInstitution = new MedicalInstitution();
        medicalInstitution.setDeptId(deptId);
        medicalInstitution.setName(name);
        //判断是否传递了是否在线的状态
        if (status != null){
            //查询设备的信息
            FreshMedicalMachine machine = new FreshMedicalMachine();
            machine.setRunningStatus(String.valueOf(status));
            List<FreshMedicalMachine> medicalMachineList = freshMedicalMachineService.selectFreshMedicalMachineList(machine);
            List<Long> institutionIdList = medicalMachineList.stream().map(m -> m.getInstitutionId()).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(institutionIdList)){
                return AjaxResult.success(new ArrayList<>());
            }
            medicalInstitution.setIdList(institutionIdList);
        }
        startPageOrderBy("id desc");
        List<MedicalInstitution> institutionList = medicalInstitutionService.selectMedicalInstitutionList(medicalInstitution);
        execDataList(institutionList);
        return AjaxResult.success(institutionList);
    }

    private void execDataList(List<MedicalInstitution> institutionList) {
        institutionList.forEach(institution ->{
            String category = sysDictDataService.selectDictLabel("institution_category", institution.getCategory());
            institution.setCategory(category);
            String level = sysDictDataService.selectDictLabel("institution_level", institution.getLevel());
            institution.setLevel(level);
            //查询设备数量
            Integer count = freshMedicalMachineService.findMachineCount(institution.getId());
            institution.setEquipmentCount(count);

            String img = "https://dyep.cc/prod-api";
            institution.setXkImg(StringUtils.isNoneBlank(institution.getXkImg()) ? img + institution.getXkImg() : "");
            institution.setMtImg(StringUtils.isNoneBlank(institution.getMtImg()) ? img + institution.getMtImg() : "");

            //查询用户信息
            SysUser sysUser = sysUserService.selectUserByUserName(institution.getCreateBy());
            if (sysUser != null){
                institution.setMobile(sysUser.getPhonenumber());
                institution.setContacts(sysUser.getUserName());
                institution.setParent(sysUser.getParentId() == 0 ? true : false);
            }
            //总处理量
            FreshMedicalMachine machine = new FreshMedicalMachine();
            machine.setInstitutionId(institution.getId());
            //设备列表
            AtomicInteger offLineCount = new AtomicInteger(0);
            List<FreshMedicalMachine> machineList = freshMedicalMachineService.selectFreshMedicalMachineList(machine);
            machineList.forEach(m ->{
                //总处理量
                Integer jgzcll = medicalEquipmentReportLogService.getMedicalHandleData(null,m.getId(),m.getMachineCode());
                m.setTotalHandle(String.valueOf(jgzcll));
                //日处理量
                Integer zuotianHandle = medicalEquipmentReportLogService.getMedicalHandleShengData("zuotian",null,m.getMachineCode());
                Integer jintianHandle = medicalEquipmentReportLogService.getMedicalHandleShengData("jintian",null,m.getMachineCode());
                Integer fresh = jintianHandle >= zuotianHandle ? jintianHandle - zuotianHandle : 0;
                m.setDayTotalHandle(String.valueOf(fresh));
            });
            institution.setEquipmentList(machineList);
            machineList.forEach(m ->{
                if ("0".equals(m.getNetworkStatus())){
                    offLineCount.addAndGet(1);
                }
                institution.setNetWorkStatus(m.getNetworkStatus());
                //设备经纬度信息
                institution.setLongitude(m.getLongitude());
                institution.setDimension(m.getDimension());
                institution.setOpCode(StringUtils.isNoneBlank(m.getOpCode()) ? img + m.getOpCode() : "");
            });
            Integer totalHandle = medicalEquipmentReportLogService.getMedicalHandleData(null,institution.getId(),null);
            Integer zuotianHandle = medicalEquipmentReportLogService.getMedicalHandleShengData("zuotian",institution.getId(),null);
            Integer jintianHandle = medicalEquipmentReportLogService.getMedicalHandleShengData("jintian",institution.getId(),null);
            Integer fresh = jintianHandle >= zuotianHandle ? jintianHandle - zuotianHandle : 0;
            institution.setTotalHandle(String.valueOf(totalHandle == null ? "0" : totalHandle));
            institution.setDayHandle(String.valueOf(fresh));
            //月处理量
            Integer benyue = medicalEquipmentReportLogService.getMedicalHandleData("benyue",institution.getId(),null);
            institution.setMonthHandle(String.valueOf(benyue));
            institution.setOffLineCount(String.valueOf(offLineCount));
            institution.setEquipmentCount(machineList.size());
            SysDept sysDept = sysDeptService.selectDeptById(institution.getDeptId());
            if (sysDept != null){
                institution.setDeptName(sysDept.getDeptName());
            }
        });
    }


    /***
     * 医疗机构详情 applet
     * @return
     */
    @GetMapping("/applet/detail")
    public AjaxResult getEquipmentReportLogData(@RequestParam Long id){
        MedicalInstitution institution = getMedicalInstitution(id);
        return AjaxResult.success(institution);
    }



    private MedicalInstitution getMedicalInstitution(Long id) {
        MedicalInstitution institution = medicalInstitutionService.selectMedicalInstitutionById(id);
        if (institution != null){
            ArrayList<MedicalInstitution> institutionList = new ArrayList<>();
            institutionList.add(institution);
            execDataList(institutionList);
            institution = institutionList.get(0);
        }
        return institution;
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:institution:list')")
    @GetMapping("/list")
    public TableDataInfo list(MedicalInstitution medicalInstitution){
        startPage();
        List<MedicalInstitution> list = medicalInstitutionService.selectMedicalInstitutionList(medicalInstitution);
        execDataList(list);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:institution:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MedicalInstitution medicalInstitution){
        List<MedicalInstitution> list = medicalInstitutionService.selectMedicalInstitutionList(medicalInstitution);
        ExcelUtil<MedicalInstitution> util = new ExcelUtil<MedicalInstitution>(MedicalInstitution.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:institution:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id){
        MedicalInstitution institution = this.getMedicalInstitution(id);
        return AjaxResult.success(institution);
    }

    /**
     * 新增【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:institution:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MedicalInstitution medicalInstitution){
        return toAjax(medicalInstitutionService.insertMedicalInstitution(medicalInstitution));
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:institution:edit')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MedicalInstitution medicalInstitution){
        return toAjax(medicalInstitutionService.updateMedicalInstitution(medicalInstitution));
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:institution:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids){
        return toAjax(medicalInstitutionService.deleteMedicalInstitutionByIds(ids));
    }
}
